package com.david.trade.api.tcp;

import com.david.trade.api.event.TcpEventSource;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 */
@Component
@Slf4j
public class NettyTcpClient {

    @Resource
    private Bootstrap bootstrap;

    @Value("${netty.tcp.server.port}")
    private int tcpPort;

    @Value(("${netty.tcp.server.ip}"))
    private String serverIp;

    private Channel channel;

    public static Map<String, TcpEventSource> tcpEventSourceMap = new HashMap<>();

    @PostConstruct
    public void connect() throws Exception {
        // 发起异步连接
        ChannelFuture future = bootstrap.connect(serverIp, tcpPort).sync();
        channel = future.channel();
        log.info("客户端连接成功");
        if (!future.isSuccess()) {
            future.cause().printStackTrace();
        }
    }

    public void stop() throws Exception {
        channel.close();
    }

    /**
     * 发送消息 使用方法即可
     * @param msg
     */
    public void sendMessage(String msgId, TcpEventSource eventSource, String msg) {
        try {
            tcpEventSourceMap.put(msgId, eventSource);
            msg = msgId + "#" + msg;
            log.info("msg: {}", msg);
            ByteBuf byteBuf = Unpooled.wrappedBuffer(msg.getBytes("utf-8"));
            channel.writeAndFlush(byteBuf);
        } catch (UnsupportedEncodingException e) {
            log.info("数据发送失败");
        }

    }
}

